import { ElMessage, ElLoading } from 'element-plus'
import useUserStore from '@/store/modules/user'

let loadingInstance
let newStatus

export function newLoading(row) {
    newStatus = row
    if (row) {
        loadingInstance = ElLoading.service({
            lock: true,
            text: '加载中...',
            background: 'rgba(0, 0, 0, 0.7)',
        });
    } else {
        loadingInstance.close()
    }
}

export async function Encapsulation(respondRes) {
    const res = await respondRes.json();
    const code = res.code
    const msg = res.msg || res.message
    newLoading(false)
    if (res.code === 200) {
        return res
    } else if (res.code === 401) {
        const userStore = useUserStore()
        ElMessage({ message: '登录状态已过期,请重新登录', type: 'error' })
        userStore.logOut().then(() => {
            location.href = '/index';
        })
        return Promise.reject('无效的会话，或者会话已过期，请重新登录。')
    } else if (code >= 500) {
        ElMessage({ message: msg, type: 'error' })
        return Promise.reject(new Error(msg))
    }
    else {
        newLoading(false)
        ElMessage({ message: msg, type: 'error' })
    }
    return respondRes
}